package tools;

import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;

import java.io.File;
import java.time.Duration;
import java.util.*;

public class FileUtil {
    public static File getProjectRoot(){
        return new File(System.getProperty("user.dir")).getParentFile();
    }

    public static File getProjectResource(String dir){
        return new File(getProjectRoot(),dir);
    }

    /**
     * 通过点击locator指定的元素来下载文件，存入download目录
     * @param driver 浏览器driver
     * @param locator 下载按钮的locator
     * @return 下载的文件
     */
    public static File downloadFile(WebDriver driver,By locator){
        File downloadPath= getProjectResource("download");
        for(File file: Objects.requireNonNull(downloadPath.listFiles(filename -> !(".gitignore".equals(filename.getName()))))){
            Assertions.assertTrue(file.delete());
        }
        PageUtil.findAndClick(driver, locator, Duration.ofSeconds(1));
        Actions actions=new Actions(driver);
        //避免遮挡下载的按钮
        actions.moveByOffset(10,10).perform();
        //最多等30秒
        for(int i=0;i<10;i++){
            if (Objects.nonNull(downloadPath.listFiles(filename -> !(".gitignore".equals(filename.getName()))))){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw  new RuntimeException(e);
                }
            }else {
                break;
            }
        }
        //取最新的文件
        Optional<File> max = Arrays.stream(Objects.requireNonNull(downloadPath.listFiles(filename -> !(".gitignore".equals(filename.getName()))))).max(Comparator.comparing(File::lastModified));
        Assertions.assertTrue(max.isPresent());
        return max.get();
    }

    /**
     * 通过向locator对应的input元素中输入filepath来做到文件上传
     * @param driver 浏览器driver
     * @param locator 输入框的locator(页面上看不见，通常在上传按钮附近)
     * @param filePath 本地文件的绝对地址
     */
    public static void uploadFile(WebDriver driver,By locator,String filePath){
        JavascriptExecutor js= (JavascriptExecutor) driver;
        PageUtil.findElement(driver,locator, Duration.ofSeconds(3))
                .ifPresent(input->{
                    js.executeScript("arguments[0].setAttribute('class','')",input);
                    PageUtil.sendKeys(driver,input,filePath);
                });
        //最多60次，每次1s
        for (int i = 0; i < 60; i++) {
            Optional<WebElement> inputOptional = PageUtil.findElement(driver,locator,Duration.ofSeconds(1));
            if (inputOptional.isPresent() && inputOptional.get().getAttribute("class").isEmpty()){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw  new RuntimeException(e);
                }
            }else {
                break;
            }
        }
    }
}
